package com.dongdongshop.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.exception.SellerLoginException;
import com.dongdongshop.exception.SellerLoginNoPassException;
import com.dongdongshop.pojo.TbItemCat;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.pojo.User;
import com.dongdongshop.service.TbSellerService;
import com.dongdongshop.service.UserService;
import jdk.jfr.events.ThrowablesEvent;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

//Rean是登录和授权逻辑的编写位置
public class LoginRealm extends AuthorizingRealm {
    @Reference
    private TbSellerService tbSellerService;
    //授权用的方法
    //这一块在进行开发的时候连接数据库即可
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //给我们访问的方法进行授权

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        //添加权限字符串
//        List<String> perms = new ArrayList<>();
//        perms.add("add");

        Subject subject = SecurityUtils.getSubject();
        //此方法就是将session里面的对象取出来
        TbSeller person = (TbSeller) subject.getPrincipal();
        return null;//info
    }
    //登录(认证)方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;//因为AuthenticationToken是一个接口不能进行做类型,所以就用的它的实现类进行定义
        String sellerId = token.getUsername();
        TbSeller u = tbSellerService.showUser(sellerId);
        if (u == null ){
            return null;
        }else if(u.getStatus().equals(1)){
            throw new SellerLoginException();//待审核
        }else if (u.getStatus().equals(0)){//审核未通过
            throw new SellerLoginNoPassException();
        }
        //SimpleAuthenticationInfo()里面第一个值是登录成功后的对象存放到session
        //第二个password是数据库里面的密码值
        //第三个是用户登录成功之后的账号名
                                                                       //盐值
        return new SimpleAuthenticationInfo(u,u.getPassword(), ByteSource.Util.bytes("abcd"),u.getSellerId());
    }
}
